package com.example.chapter10media;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView stateView, saveView;
    private Button btnStart, btnStop, btnPlay, btnFinish;
    private MediaRecorder myRecorder;
    private MediaPlayer player;
    private File audioFile;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //this.setTitle("录制音频文件示例");
        stateView = (TextView) this.findViewById(R.id.view_state);
        saveView = (TextView) this.findViewById(R.id.view_save);
        stateView.setText("准备开始");
        btnStart = (Button) this.findViewById(R.id.btn_start);
        btnStop = (Button) this.findViewById(R.id.btn_stop);
        btnPlay = (Button) this.findViewById(R.id.btn_play);
        btnFinish = (Button) this.findViewById(R.id.btn_finish);

        btnStart.setOnClickListener(this);
        btnStop.setOnClickListener(this);
        btnFinish.setOnClickListener(this);
        btnPlay.setOnClickListener(this);
        checkPermission();
    }

    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.btn_start:
                //开始录制
                //先实例化一个MediaRecorder对象，然后进行相应的设置
                myRecorder = new MediaRecorder();

                //指定AudioSource 为MIC，从麦克风获取音频，这是最常用的
                myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                //Request requires android.permission.RECORD_AUDIO，麦克风权限需要手工到手机里面再设置

                //myRecorder.reset();//重置，加上就出错
                //指定输出格式和编码方式
                myRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
                myRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);

                //myRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
                //Android2.2及其以后版本采用该方式设置输出格式和编码格式
                //设置录音文件的存储位置  特别说明：Environment.getExternalStorageDirectory()不仅需要外部存储的读写权限，还需要外部存储的管理权限android.permission.MANAGE_EXTERNAL_STORAGE
                audioFile = new File(getExternalFilesDir(null),  + System.currentTimeMillis() + "录音.m4a");

                myRecorder.setOutputFile(audioFile.getAbsolutePath());
                Log.d("我的提示", audioFile.getAbsolutePath());

                try {
                    myRecorder.prepare();  //缓冲
                } catch (Exception e) {
                    e.printStackTrace();
                    saveView.setText(e.toString());
                }
                myRecorder.start();         //开始录制
                stateView.setText("正在录制");
                saveView.setText("录音文件保存在：" + audioFile.getAbsolutePath());
                btnStart.setEnabled(false);
                btnPlay.setEnabled(false);
                btnStop.setEnabled(true);
                btnFinish.setEnabled(true);
                break;
            case R.id.btn_stop:
                myRecorder.stop();
                myRecorder.release();

                //然后我们可以将我们的录制文件存储到MediaStore中
/*                ContentValues values = new ContentValues();
                values.put(MediaStore.Audio.Media.TITLE, "this is my first record-audio");
                values.put(MediaStore.Audio.Media.DATE_ADDED, System.currentTimeMillis());
                values.put(MediaStore.Audio.Media.DATA, audioFile.getAbsolutePath());
                fileUri = this.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);*/
                //录制结束后，我们实例化一个MediaPlayer对象，然后准备播放
                player = new MediaPlayer();
                player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                    @Override
                    public void onCompletion(MediaPlayer arg0) {
                        // 播放结束，更新按钮的状态
                        btnPlay.setEnabled(true);
                        btnStart.setEnabled(true);
                        btnStop.setEnabled(false);
                    }
                });

                //准备播放
                try {
                    player.setDataSource(audioFile.getAbsolutePath());
                    player.prepare();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                //更新状态
                stateView.setText("准备回放");
                btnPlay.setEnabled(true);
                btnStart.setEnabled(true);
                btnStop.setEnabled(false);
                break;
            case R.id.btn_play:
                //播放录音。注意，在录音结束的时候，已经实例化了MediaPlayer，做好了播放的准备
                player.start();
                //更新状态
                stateView.setText("正在播放");
                btnStart.setEnabled(false);
                btnStop.setEnabled(false);
                btnPlay.setEnabled(false);
                //在播放结束的时候也要更新状态
                break;
            case R.id.btn_finish:
                this.finish();
                break;
        }
    }

    /**
     * 权限申请
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE};
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, permissions, 200);
                    return;
                }
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == 200) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivityForResult(intent, 200);
                    return;
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 200) {
            checkPermission();
        }
    }
}